package top.marken.demo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import top.marken.demo.mapper.OrderMapper;
import top.marken.demo.mapper.UserMapper;
import top.marken.demo.entity.Order;
import top.marken.demo.entity.User;
import top.marken.demo.service.UserService;
import top.marken.demo.util.Page;
import java.util.Date;
import java.util.List;

public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public boolean login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (null == user) return false;
        return user.getPassword().equals(password);
    }

    @Override
    public User userInfo(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public List<Order> userOrders(int uId) {
        return orderMapper.findOrdersByUId(uId);
    }

    @Override
    public boolean doOrder(Order order) {
        return orderMapper.insertOne(order);
    }

    @Override
    public boolean updateOrder(Order order) {
        return orderMapper.updateOne(order);
    }

    @Override
    public boolean deleteOrder(int id) {
        return orderMapper.deleteOne(id);
    }

    @Override
    public Order getOrder(int id) {
        return orderMapper.findOrderById(id);
    }

    @Override
    public boolean order(String name, double price, int uId) {
        return orderMapper.insertOne(new Order(null,new Date(),price,uId,name));
    }

    @Override
    public Page<Order> userOrdersPage(int uId, int page, int size) {
        int total = orderMapper.getTotalByUId(uId);
        int pageTotal = (int) Math.ceil(total / size);
        int start = (page - 1) * size;
        List<Order> orders = orderMapper.getPageOrdersByUId(uId,start,size);
        if (orders.size() == 0) return null;
        Page<Order> orderPage = new Page<>();
        orderPage.setTotal(pageTotal);
        orderPage.setPage(page);
        orderPage.setSize(size);
        orderPage.setRows(orders);
        return orderPage;
    }

    public UserMapper getUserDao() {
        return userMapper;
    }

    public void setUserDao(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public OrderMapper getOrderDao() {
        return orderMapper;
    }

    public void setOrderDao(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }
}
